<template>
  <div class="internship-container">
    <el-card shadow="never">
      <!-- 搜索栏 -->
      <div class="filter-header">
        <el-input
          v-model="filter.id"
          placeholder="编号"
          style="width: 120px"
          class="filter-item"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-input
          v-model="filter.name"
          placeholder="名称"
          style="width: 120px; margin-left: 10px"
          class="filter-item"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-input
          v-model="filter.company"
          placeholder="实习单位"
          style="width: 140px; margin-left: 10px"
          class="filter-item"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" style="margin-left: 10px" @click="handleSearch">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button style="margin-left: 10px" @click="handleReset">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="filteredData"
        style="width: 100%"
        header-row-class-name="table-header"
        stripe
        border
      >
        <el-table-column prop="id" label="编号" width="80" align="center" />
        <el-table-column prop="name" label="名称" width="120" />
        <el-table-column prop="start_time" label="开始时间" width="120" />
        <el-table-column prop="end_time" label="结束时间" width="120" />
        <el-table-column label="实习单位" width="150">
          <template #default="scope">
            <div>
              {{ scope.row.company || '-' }}
              <span v-if="scope.row.company_extra" style="color: #999; font-size: 12px">
                ({{ scope.row.company_extra }})
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="周报成绩" width="100" align="center">
          <template #default="scope">
            <span :class="{'score-highlight': scope.row.weekly_score && scope.row.weekly_score !== '-'}">
              {{ scope.row.weekly_score || '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="总结成绩" width="100" align="center">
          <template #default="scope">{{ scope.row.summary_score || '-' }}</template>
        </el-table-column>
        <el-table-column label="总成绩" width="100" align="center">
          <template #default="scope">{{ scope.row.total_score || '-' }}</template>
        </el-table-column>
        <el-table-column label="最终成绩" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="getScoreTagType(scope.row.final_score)"
              size="small"
              effect="light"
            >
              {{ scope.row.final_score || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div class="pagination-info">
        第 1 到 {{ filteredData.length }} 条，共 {{ filteredData.length }} 条记录。
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`编辑实习信息 - ${editForm.name}`"
      width="50%"
      @closed="handleDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="编号" prop="id">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入实习名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            v-model="editForm.start_time"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="editForm.end_time"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            :disabled-date="disabledEndDate"
          />
        </el-form-item>
        <el-form-item label="实习单位" prop="company">
          <el-input v-model="editForm.company" placeholder="请输入实习单位" />
        </el-form-item>
        <el-form-item label="实习单位补充">
          <el-input v-model="editForm.company_extra" placeholder="可填写详细公司信息" />
        </el-form-item>
        <el-form-item label="周报成绩">
          <el-input-number
            v-model="editForm.weekly_score"
            :precision="2"
            :step="0.1"
            :min="0"
            :max="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="总结成绩">
          <el-input v-model="editForm.summary_score" disabled />
        </el-form-item>
        <el-form-item label="总成绩">
          <el-input v-model="editForm.total_score" disabled />
        </el-form-item>
        <el-form-item label="最终成绩">
          <el-input v-model="editForm.final_score" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search,
  Refresh,
  Edit
} from '@element-plus/icons-vue'

// 数据状态
const filter = ref({
  id: '',
  name: '',
  company: ''
})

const tableData = ref([
  {
    id: 13,
    name: '顶岗实习',
    start_time: '2020-08-03',
    end_time: '2020-10-15',
    company: '360',
    weekly_score: '-',
    summary_score: '-',
    total_score: '-',
    final_score: '-'
  },
  {
    id: 14,
    name: '顶岗实习',
    start_time: '2020-08-29',
    end_time: '2020-10-22',
    company: '1',
    weekly_score: '20',
    summary_score: '40.00',
    total_score: '32.0000',
    final_score: '不及格'
  },
  {
    id: 15,
    name: '顶岗实习',
    start_time: '2021-12-01',
    end_time: '2023-02-01',
    company: 'C',
    company_extra: '北京某公司',
    weekly_score: '-',
    summary_score: '-',
    total_score: '-',
    final_score: '-'
  }
])

const originalData = ref([])
const dialogVisible = ref(false)
const formRef = ref(null)

const editForm = ref({
  id: '',
  name: '',
  start_time: '',
  end_time: '',
  company: '',
  company_extra: '',
  weekly_score: 0,
  summary_score: '',
  total_score: '',
  final_score: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入实习名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  company: [
    { required: true, message: '请输入实习单位', trigger: 'blur' }
  ]
}

// 计算属性
const filteredData = computed(() => {
  return tableData.value.filter(item => {
    const idMatch = filter.value.id ? item.id.toString().includes(filter.value.id) : true
    const nameMatch = filter.value.name ? item.name.includes(filter.value.name) : true
    const companyMatch = filter.value.company ? 
      (item.company + (item.company_extra || '')).toLowerCase().includes(filter.value.company.toLowerCase()) : true
    return idMatch && nameMatch && companyMatch
  })
})

// 生命周期钩子
onMounted(() => {
  originalData.value = JSON.parse(JSON.stringify(tableData.value))
})

// 方法
const getScoreTagType = (score) => {
  if (score === '优秀' || score === '良好') return 'success'
  if (score === '及格') return 'warning'
  if (score === '不及格') return 'danger'
  return 'info'
}

const disabledEndDate = (time) => {
  if (!editForm.value.start_time) return false
  return time < new Date(editForm.value.start_time)
}

const handleSearch = () => {
  ElMessage.success('搜索完成')
}

const handleReset = () => {
  filter.value = {
    id: '',
    name: '',
    company: ''
  }
  tableData.value = JSON.parse(JSON.stringify(originalData.value))
  ElMessage.success('已重置')
}

const handleEdit = (row) => {
  editForm.value = {
    ...JSON.parse(JSON.stringify(row)),
    weekly_score: row.weekly_score === '-' ? 0 : parseFloat(row.weekly_score)
  }
  dialogVisible.value = true
}

const handleDialogClosed = () => {
  formRef.value?.resetFields()
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    const index = tableData.value.findIndex(item => item.id === editForm.value.id)
    if (index !== -1) {
      const weeklyScoreDisplay = editForm.value.weekly_score === 0 ? '-' : editForm.value.weekly_score.toString()
      
      tableData.value[index] = {
        ...editForm.value,
        weekly_score: weeklyScoreDisplay
      }
      
      ElMessage.success('修改成功')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.internship-container {
  padding: 20px;
}

.filter-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-item {
  margin-left: 10px;
}

.table-header th {
  background-color: #f5f7fa !important;
  font-weight: 600;
}

.pagination-info {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 13px;
  text-align: center;
}

.el-button [class*="el-icon-"] {
  margin-right: 5px;
}

.el-table {
  margin-top: 20px;
}

.score-highlight {
  color: #409eff;
  font-weight: 500;
}

.el-tag {
  min-width: 60px;
  justify-content: center;
}
</style>